{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "04272d34-7c5b-4cde-96e2-ab35a1488434",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NAME=\"CentOS Stream\"\n",
      "VERSION=\"8\"\n",
      "ID=\"centos\"\n",
      "ID_LIKE=\"rhel fedora\"\n",
      "VERSION_ID=\"8\"\n",
      "PLATFORM_ID=\"platform:el8\"\n",
      "PRETTY_NAME=\"CentOS Stream 8\"\n",
      "ANSI_COLOR=\"0;31\"\n",
      "CPE_NAME=\"cpe:/o:centos:centos:8\"\n",
      "HOME_URL=\"https://centos.org/\"\n",
      "BUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\n",
      "REDHAT_SUPPORT_PRODUCT=\"Red Hat Enterprise Linux 8\"\n",
      "REDHAT_SUPPORT_PRODUCT_VERSION=\"CentOS Stream\"\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# paramiko模块用法\n",
    "# 简介：paramiko模块是一个用于连接SSH服务器的Python模块，可以进行交互和非交互式的命令操作和文件操作。paramiko内部依赖pycrypto模块，安装方法：pip install paramiko\n",
    "# 安装错误解决办法：可能是因为系统没有安装pycrypto模块、python-dev或gcc软件包导致。安装pycrypto模块使用pip install pycrypto；centos/redhat系统使用sudo yum install python-dev gcc -y，ubuntu/debian系统使用sudo apt install python-dev gcc -y安装相关开发包。\n",
    "\n",
    "import paramiko\n",
    "import time\n",
    "\n",
    "#实例化一个ssh客户端对象\n",
    "example=paramiko.SSHClient() \n",
    "\n",
    "#加载本地主机密钥\n",
    "#example.load_system_host_keys() \n",
    "\n",
    "#自动添加密钥到本地主机\n",
    "example.set_missing_host_key_policy(paramiko.AutoAddPolicy())  \n",
    "\n",
    "#创建连接\n",
    "example.connect(hostname='192.168.0.100',port=22,username='root',key_filename=r'/home/test/.ssh/id_rsa.pub')  \n",
    "\n",
    "#启功一个交互式shell,适用于执行多个命令\n",
    "# cli=example.invoke_shell() \n",
    "# #向shell发送指令\n",
    "# cli.send('free -h\\\\n')  \n",
    "# cli.send('df -h')\n",
    "# #结果转码并输出\n",
    "# print(cli.recv(9999).decode())  \n",
    "\n",
    "#执行命令,适用于执行单个命令\n",
    "stdin,stdout,stderr=example.exec_command(r'cat /etc/os-release') \n",
    "#将执行结果转码并输出\n",
    "print(stdout.read().decode())  \n",
    "\n",
    "example.close()  #关闭连接"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aaffdd36-be3a-4286-b1d2-3187987e74c7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
